package com.simtop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.Key;
import com.simtop.common.ServerResponse;
import com.simtop.dao.CountDao;
import com.simtop.dao.UserDao;
import com.simtop.pojo.*;
import com.simtop.service.JwtLoginService;
import com.simtop.service.UserService;
import com.simtop.util.*;
import com.simtop.vo.UserParamsVo;
import com.simtop.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;


/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@CrossOrigin //todo 跨域问题
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;


    @Autowired
    private UserDao userDao;


//    @RequestMapping(value = "/updateMD5Password",method = RequestMethod.GET)
//    public ServerResponse<String> updateMD5Password(){
//        return userService.updateMD5Password();
//    }

    /**
     * 前台用户注册接口
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserVo userVo, HttpServletRequest request) throws UnsupportedEncodingException {
        /**
         * 接受前台时候出现乱码问题 进行硬编码 todo 2019年8月19日17:38:20 中文参数乱码问题 important
         */
        System.out.println("接收到的前台参数为："+userVo);
//        String school = new String(request.getParameter("school").getBytes("ISO-8859-1"),"utf-8");
//        String province = new String(request.getParameter("province").getBytes("ISO-8859-1"),"utf-8");
//        String city = new String(request.getParameter("city").getBytes("ISO-8859-1"),"utf-8");
//        String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"utf-8");
//        userVo.setSchool(school);
//        userVo.setProvince(province);
//        userVo.setCity(city);
//        userVo.setUsername(username);
        return userService.register(userVo);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     * @return
     */
    @RequestMapping(value = "/checkCode",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode( String email){
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }

    /**
     * ilab平台用户登陆 2019年10月11日15:50:32
     */
    @RequestMapping(value = "/ilab/login",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login( HttpServletRequest request,HttpServletResponse response,@RequestBody String data){
        JSONObject jsonObject=JSON.parseObject(data);
        String jwt = jsonObject.getString("ticket");
        try {
            logger.info("ilab平台用户进入了{}",jwt);
            // 解析token获取包含username的json字符串
            String appid=String.valueOf(Key.issuerId);
            String AesKey=Key.AesKey;
            String Ticket= URLDecoder.decode(jwt,"UTF-8");
            String SIGNATURE=CipherUtil.generatePassword(Ticket+appid+AesKey);
            //测试地址和正式地址 http://202.205.145.156:8017->http://www.ilab-x.com
            System.out.println("http://www.ilab-x.com/open/api/v2/token?ticket="+jwt+"&appid="+appid+"&signature="+SIGNATURE);
            String code = HttpUtil.loadJSON("http://www.ilab-x.com/open/api/v2/token?ticket="+jwt+"&appid="+appid+"&signature="+SIGNATURE);
            // todo ilabJson乱码了！ 2019年10月12日09:39:58
            JSONObject o = JSONObject.parseObject(code);
            logger.info("ilab传过来的ticket解析之后的{}",o);
            Integer codeCheck=o.getInteger("code");
            if(codeCheck!=0){
                //todo codeCheck是ilab返回的数据信息反馈,案例：({"code":0, "access_token":"4hCwDHmIAf8Bj+TVe7GBVUaLOY0rJiDyWtCmNhixIsBJnZLiAPhmYc0vBLr592Zj","create_time":1598230461000,"create_time_display":"2020-08-24 08:54:21","expires_time":1598237661236,"expires_time_display":"2020-08-24 10:54:21", "un":"username", "dis":"用户姓名"})
                //todo 判断用户ilab返回的ticket是否继续有效(如果不是为0的话，那就是失效；0为ticket有效)
                return ServerResponse.createByErrorMsg("新增ilab平台用户失败");
            }
            String loginName = o.getString("un");
            String username  = loginName;
            //如果数据库存在登陆用户名 则直接返回
            //如果数据库存在登陆用户名 则直接返回
            User user =  userService.selectUserByLoginName(loginName);
            if(user != null){
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"),"UTF-8"));
                System.out.println(URLEncoder.encode(o.getString("access_token"),"UTF-8"));
                String token1 = JwtUtil.sign(user,60L*1000*60*24L);//token有效期24小时
                Operate operate = new Operate("ilab用户登录操作",user.getUsername(),"登录成功",null, null,user.getRoleId());
                userDao.insertOperate(operate);
                return ServerResponse.createBySuccess(user.getExercises()+"",token1);
            }
            String access_token=o.getString("access_token");
            //todo 不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            userVo.setSchool("ilab平台用户");
            userVo.setProvince("ilab平台");
            userVo.setCity("ilab平台");
            userVo.setRoleId(4);//学生
            userVo.setPassword("12345");
            userVo.setEmail("ilab@163.com");
            System.out.println("acess_token="+URLEncoder.encode(access_token,"UTF-8"));
            //必须要把access_token通过encode进行解密（UTF-8）
            userVo.setAccessToken(URLEncoder.encode(access_token,"UTF-8"));
            int id= userService.ilabInsertUser(userVo);
            userVo.setId(id);
            Operate operate = new Operate("ilab用户登录操作",userVo.getUsername(),"登录成功",null, null,userVo.getRoleId());
            userDao.insertOperate(operate);
            String token1 = JwtUtil.sign(userVo,60L*1000*60*24L);//token1有效期24小时
            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("新增ilab平台用户失败");
    }

    /**
     * 用户登录 成功后给前台返回一个token,后面需要拿这个token去验证
     * todo 用户类型：ilab用户 2019年9月24日15:34:07
     * 前台传入
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody UserVo userVo, HttpServletResponse response){
        // todo 如果是管理员或者评审专家 直接登陆 admin 123
        System.out.println("userVo"+userVo.getLoginName());
        System.out.println("userVoRoleId"+userVo.getRoleId());
        System.out.println("userVoPassword"+userVo.getPassword());
        if(userVo.getRoleId()==1||userVo.getRoleId()==3){
            User user = new User();
            //角色id
            user.setRoleId(userVo.getRoleId());
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);
        }
        User user = new User();
        //角色id
        user.setRoleId(userVo.getRoleId());
        //登录名
        user.setLoginName(userVo.getLoginName());
        //登陆密码
        user.setPassword(userVo.getPassword());
        return jwtLoginService.login(user);
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     *
     */
    @RequestMapping(value = "/forget_checkCode",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode( String email){
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.PUT)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo){
        return userService.updatePassword(userVo);
    }

    /**
     * 用户管理 查看所有的数据
     */
    @RequestMapping(value = "/backend/findAll",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findAll(Integer userId, HttpServletRequest request, Integer pageNum, Integer pageSize){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userService.findAll();
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }
    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, Integer userId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.insertBackUser(userVo);
    }

    /**
     * 根据用户id删除User表数据
     */

    @RequestMapping(value = "/deleteByUserId",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        logger.info("管理员删除用户,编号为{}",id);
        return userService.deleteByUserId(id);
    }

    /**
     * 修改用户信息
     * @param userVo
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/backend/update",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(@RequestBody UserVo userVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.updateBackendUser(userVo);
    }

    /**
     * 根据用户id查询用户信息
     */

    @RequestMapping(value = "/backend/findById",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, Integer id){
        String token = request.getHeader("Authorization");
        if(token == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.findById(id);
    }

    /**
     * 用户查询功能(学校、姓名、登录名查询)
     */
    @RequestMapping(value = "/backend/findByParams",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(HttpServletRequest request, UserParamsVo params, Integer pageNum, Integer pageSize){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userService.findByParams(params);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 获取用户操作信息
     */
    @RequestMapping(value = "/getOperateInfo",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getOperateInfo(HttpServletRequest request,@RequestBody String data){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject= JSON.parseObject(data);
        Integer pageNum=jsonObject.getInteger("pageNum");
        Integer pageSize=jsonObject.getInteger("pageSize");
        return userService.getOperateInfo(pageNum,pageSize);
    }

    /**
     *下载操作日志
     * @param response
     */
    @RequestMapping(value = "/downLoadOperateInfo",method = RequestMethod.GET)
    @ResponseBody
    public void downLoadOperateInfo(HttpServletResponse response){
        ServletOutputStream out = null;
        List<DownOperate> downOperateList=userService.downLoadOperateInfo();
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "操作日志记录";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelUtils.writeExcel(out, DownOperate.class,downOperateList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 统计功能：统计用户总数量
     */
    // @RequestMapping(value = "/userAccount",method = RequestMethod.GET)
    @GetMapping("/userAccount")
    @ResponseBody
    public ServerResponse<Integer> userAccount(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.accountUser();
    }


    /**
     * 下载学生实验成绩
     * @param response
     */
    @RequestMapping(value = "/uploadExperimentModule",method = RequestMethod.GET)
    public void uploadExperimentModule(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            List<ExperimentModules> experimentModulesList=userService.uploadExperimentModule();
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "导出数据";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelUtils.writeExcel(out, ExperimentModules.class,experimentModulesList);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
